/* eslint-disable indent */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-negated-condition */
/* eslint-disable react/no-direct-mutation-state */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Popconfirm, Table, Button, Form, Row, Col, Card, Spin, message as msg} from 'antd';
import {getDetail, getSubDetail, getBanks} from './api';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions, uuid} from './utils';
import {formatAmount} from '../utils';
import {PERMISSION} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import InputAmount from '../common/InputAmount';
import styles from './style.css';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import {currency, saleOrderPriceTerms, paymentType, saleOrderTransportTypeForKd} from '../Enum';
import ImportPartPanel from './ImportPartPanel';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        valiSaleOrder: false,
        bankList: [],
        data: {
            currency: currency.USD,
            salesOrderPriceTerms: saleOrderPriceTerms.FOB,
            tradeMethodId: '3cd4b3e5-8e22-4391-91fc-b3fb51c2d120'
        },
        details: [],
        saleProformaPartDetails: [],
        showPartImportPanel: false
    };
    componentDidMount() {
        this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok) {
                        const condition = {
                            brandId: res.data.brandId,
                            tradeMethodId: this.state.data.tradeMethodId
                        };
                        this.getBanks(condition, res.data.bankId);
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.subPIPlacements,
                            saleProformaPartDetails: res.data.subPIDetails
                        });
                    } else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    handleFilterChange = (value, name) => {
        if(this.state.data.bankId && name === 'dealerId') {
            const id = value;
            const newArr = this.state.bankList.filter(d => d.value === id);
            this.state.data.bankNameEng = newArr[0].engName;
            this.state.data.bankAccount = newArr[0].account;
            this.state.data.swift = newArr[0].swift;
        }
        if(name === 'bankId') {
            const id = value;
            const newArr = this.state.bankList.filter(d => d.value === id);
            this.state.data.bankNameEng = newArr[0].engName;
            this.state.data.bankAccount = newArr[0].account;
            this.state.data.swift = newArr[0].swift;
        }
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    
    // eslint-disable-next-line react/sort-comp
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    
    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data, this.state.details, this.state.saleProformaPartDetails);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data, this.state.details, this.state.saleProformaPartDetails).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    
    onSelectDealer = (condition = {}) => {
        if(this.props.initEnum.brands.length === 1)
            this.state.data.brandId = this.props.initEnum.brands[0].value;
        if(!this.state.data.brandId)
            msg.warn(this.props.intl.formatMessage({
                id: 'NewPanel.message.choseBrand',
                defaultMessage: '请先选择品牌'
            }));
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                    address: condition.address,
                    zipCode: condition.zipCode,
                    contactNumber: condition.contactPhone,
                    country: condition.countryName,
                    marketDepartmentName: condition.marketDepartmentName,
                }
            };
        });
        if(condition.id) {
            const queryCondition = {
                dealerId: condition.id,
                brandId: this.state.data.brandId
            };
            this.queryDetail(queryCondition);
        }
        if(!condition.id) {
            const newData = cloneDeep(this.state.data);
            this.setState({
                data: {
                    ...newData,
                    dealerId: '',
                    productionMonth: '',
                    title: '',
                    cargoDescription: '',
                    model: '',
                    supplierId: '',
                    currency: undefined,
                    tradeMethodId: '',
                    salesOrderPriceTerms: undefined,
                    paymentType: undefined,
                    deliveryTerms: undefined,
                    shippingPortId: '',
                    destinationPort: '',
                    bankId: '',
                    engName: '',
                    account: '',
                    swift: '',
                    address: '',
                    zipCode: '',
                    contactNumber: '',
                    country: '',
                    marketDepartmentName: '',
                }
            });
        }
    };
    getBanks = (condition, bankId) => {
        getBanks(condition).then(res => {
            if(res.ok) {
                const bankLists = res.data.content.map(item => ({
                    text: `${item.name}`,
                    value: item.id,
                    engName: item.engName,
                    swift: item.swift,
                    account: item.account
                }));
                this.setState({
                    bankList: bankLists
                });
                const id = bankId;
                const newArr = bankLists.filter(d => d.value === id);
                if(newArr.length !== 0) {
                    this.state.data.bankNameEng = newArr[0].engName;
                    this.state.data.bankAccount = newArr[0].account;
                    this.state.data.swift = newArr[0].swift;
                    this.state.data.bankId = id;
                }
                if(newArr.length === 0)
                    this.state.data.bankId = null;
            }
        });
    }
    queryDetail = queryCondition => {
        getSubDetail(queryCondition).then(res => {
            if(res.ok) {
                if(this.state.data.brandId) {
                    const condition = {
                        brandId: this.state.data.brandId,
                        tradeMethodId: this.state.data.tradeMethodId,
                    };
                    if(this.state.bankList.length === 0)
                        this.getBanks(condition, res.data.bankId);
                        if(res.data.bankId && this.state.bankList.length !== 0) {
                            const id = res.data.bankId;
                            const newArr = this.state.bankList.filter(d => d.value === id);
                            this.state.data.bankNameEng = newArr[0].engName;
                            this.state.data.bankAccount = newArr[0].account;
                            this.state.data.swift = newArr[0].swift;
                        }
                }
                if(!this.state.data.brandId) {
                    const condition = {
                        brandId: this.props.initEnum.brands[0].value,
                        tradeMethodId: this.state.data.tradeMethodId,
                    };
                    if(this.state.bankList.length === 0)
                        this.getBanks(condition, res.data.bankId);
                        if(res.data.bankId && this.state.bankList.length !== 0) {
                            const id = res.data.bankId;
                            const newArr = this.state.bankList.filter(d => d.value === id);
                            this.state.data.bankNameEng = newArr[0].engName;
                            this.state.data.bankAccount = newArr[0].account;
                            this.state.data.swift = newArr[0].swift;
                        }
                }
                this.setState(state => {
                    const newData = cloneDeep(state.data);
                    return {
                        hasOperat: true,
                        data: {
                            ...newData,
                            title: res.data.title,
                            productionMonth: res.data.productionMonth,
                            cargoDescription: res.data.cargoDescription,
                            model: res.data.model,
                            supplierId: res.data.supplierId,
                            currency: res.data.currency,
                            salesOrderPriceTerms: res.data.salesOrderPriceTerms,
                            paymentType: res.data.paymentType,
                            deliveryTerms: res.data.deliveryTerms,
                            shippingPortId: res.data.shippingPortId,
                            destinationPort: res.data.destinationPort,
                            address: res.data.address,
                            zipCode: res.data.zipCode,
                            country: res.data.country,
                            marketDepartmentName: res.data.marketDepartmentName,
                            bankId: res.data.bankId,
                        }
                    };
                });
            }
        });
    }
    onClickImportPartBtn = () => {
        this.setState({showPartImportPanel: true});
    }
    onClosePartImportPanel = () => {
        this.setState({showPartImportPanel: false});
    }
    onDeleteDetails = e => {
        const id = e.target.dataset.partCode;
        const tmp = this.state.saleProformaPartDetails.filter(d => d.partCode !== id);
        if(this.state.saleProformaPartDetails.length !== 0)
            this.setState({
                saleProformaPartDetails: [...tmp],
                hasOperat: true,
            });
    }
    onDeleteDetailAll = () => {
        this.setState({
            saleProformaPartDetails: [],
            hasOperat: true,
        });
    }
    onUpdateQuantity = (quantity, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    quantity,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    onPartCodeChange = (partCode, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    partCode,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    onPartNameInChineseChange = (partNameInChinese, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    partNameInChinese,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    onPartNameInEnglishChange = (partNameInEnglish, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    partNameInEnglish,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    priceOnChange = (price, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    price,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    onRemarkChange = (remark, id) => {
        const details = this.state.saleProformaPartDetails || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    remark,
                });
            return d;
        });
        this.setState({
            saleProformaPartDetails: tmp,
            hasOperat: true
        });
    }
    onPartImportChange = records => {
        if(records.payload) {
            const retailDetails = [];
            records.payload.content.forEach(r => {
                const index = retailDetails.findIndex(v => v.partCode === r.partCode);
                if(index === -1)
                    retailDetails.push({
                        id: r.id,
                        partCode: r.partCode,
                        partNameInChinese: r.partNameInChinese,
                        partNameInEnglish: r.partNameInEnglish,
                        quantity: r.quantity,
                        price: r.price,
                        remark: r.remark
                    });
            });
            this.setState({
                saleProformaPartDetails: [...retailDetails],
                hasOperat: true,
                showPartImportPanel: false,
            });
        }
    }
    onPlacementChange = (placement, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    placement,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onQuantityChange = (quantity, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    quantity,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onPriceChange = (price, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    price,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onChangeRemark = (remark, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    remark,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickAddDetailBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid(),
                    quantity: 0,
                    price: 0,
                }
            ]
        });
    };
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true,
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== id);
        this.setState({
            details: [...tmp],
            hasOperat: true,
        });
    }
    render() {
        const {data, saleProformaPartDetails, details} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validatePICode = !data.pICode && this.state.validate ? 'error' : null;
        const validateTitle = !data.title && this.state.validate ? 'error' : null;
        const validateCargoDescription = !data.cargoDescription && this.state.validate ? 'error' : null;
        const validateModel = !data.model && this.state.validate ? 'error' : null;
        const validateCurrency = !data.currency && this.state.validate ? 'error' : null;
        //const validateTradeMethod = !data.tradeMethodId && this.state.validate ? 'error' : null;
        const validateSalesOrderPriceTerms = !data.salesOrderPriceTerms && this.state.validate ? 'error' : null;
        const validatePaymentType = !data.paymentType && this.state.validate ? 'error' : null;
        const validateDeliveryTerms = !data.deliveryTerms && this.state.validate ? 'error' : null;
        const validateShippingPort = !data.shippingPortId && this.state.validate ? 'error' : null;
        const validateDestinationPort = !data.destinationPort && this.state.validate ? 'error' : null;
        const validateBank = !data.bankId && this.state.validate ? 'error' : null;
        const validateProductionMonth = !data.productionMonth && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        let totalAmount = 0;
        let totalQuantity = 0;
        let totalAmountSum = 0;
        let totalQuantitySum = 0;
        if(saleProformaPartDetails)
            saleProformaPartDetails.forEach(v => {
                totalAmount += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                totalQuantity += v.quantity;
            });
        if(details)
            details.forEach(v => {
                    totalAmountSum += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                    totalQuantitySum += v.quantity;
                });
            const columns = [{
                title: formatMessage({
                    id: 'newPanel.column.placement',
                    defaultMessage: '配置'
                }),
                dataIndex: 'placement',
                render: (text, record) => {
                    const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                        return (<FormItem {...validate}>
                            <TextInput
                                id={record.id}
                                name="placement"
                                value={text}
                                onBlur={this.onPlacementChange}/>
                        </FormItem>);
                }
            }, {
                title: formatMessage({
                    id: 'newPanel.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
                render: (text, record) => {
                    const validate = (!text || text === undefined) || text === 0 ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <LocalizeInputNumber
                            min={0}
                            id={record.id}
                            precision={0}
                            value={text} onChange={this.onQuantityChange}/>
                    </FormItem>);
                }
            }, {
                title: formatMessage({
                    id: 'newPanel.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                render: (text, record) => {
                    const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <InputAmount
                            id={record.id}
                            value={record.price}
                            onChange={this.onPriceChange}/>
                    </FormItem>);
                }
            }, {
                title: formatMessage({
                    id: 'newPanel.column.totalPrice',
                    defaultMessage: '金额'
                }),
                dataIndex: 'totalPrice',
                render: (text, record) => formatAmount((record.price ? record.price : 0) * (record.quantity ? record.quantity : 0))
            }, {
                title: formatMessage({
                    id: 'newPanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
                render: (text, record) => (<FormItem>
                    <TextInput
                        id={record.id}
                        name="remark"
                        value={text}
                        onBlur={this.onChangeRemark}/>
                </FormItem>)
            }, {
                title: details.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'newPanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'newPanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                    id: 'newPanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            }];
        const partColumns = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <TextInput
                            id={record.id}
                            name="partCode"
                            value={text}
                            onBlur={this.onPartCodeChange}/>
                    </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInChinese',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partNameInChinese',
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <TextInput
                            id={record.id}
                            name="partNameInChinese"
                            value={text}
                            onBlur={this.onPartNameInChineseChange}/>
                    </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInEnglish',
                defaultMessage: '备件英文名称'
            }),
            dataIndex: 'partNameInEnglish',
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <TextInput
                            id={record.id}
                            name="partNameInEnglish"
                            value={text}
                            onBlur={this.onPartNameInEnglishChange}/>
                    </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                        <LocalizeInputNumber
                            min={0}
                            id={record.id}
                            precision={0}
                            value={text} onChange={this.onUpdateQuantity}/>
                    </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: (text, record) => {
                const validate = (!text || text === undefined) ? {validateStatus: 'error'} : null;
                    return (<FormItem {...validate}>
                    <InputAmount
                        id={record.id}
                        value={formatAmount(record.price)}
                        onChange={this.priceOnChange}/>
                </FormItem>);
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: (t, r) => formatAmount((r.quantity ? r.quantity : 0) * (r.price ? r.price : 0))
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
            render: (text, record) => (<FormItem>
                <TextInput
                    id={record.id}
                    name="remark"
                    value={text}
                    onBlur={this.onRemarkChange}/>
            </FormItem>)
        }, {
            title: saleProformaPartDetails.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.validation.isDeleteAll',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteDetailAll} >
                        <a>{formatMessage({
                            id: 'newPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetails}>{formatMessage({
                id: 'newPanel.validation.deleteDetail',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {this.props.initEnum.brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代编号'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        <DealerSelectPanel
                                            value={dealerInfo}
                                            name="dealerId"
                                            onChange={this.handleFilterChange}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.batchNumber',
                                            defaultMessage: '批次号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {!this.props.id ? <span>{this.props.intl.formatMessage({
                                            id: 'newPanel.form.noNumber',
                                            defaultMessage: '尚未生成'
                                        })}</span> : <TextInput
                                            name="batchNumber"
                                            value={data.batchNumber}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.piCode',
                                            defaultMessage: '发票号'
                                        })} {...FORM_OPTIONS.item} validateStatus={validatePICode} required>
                                        <TextInput
                                            name="piCode"
                                            value={data.piCode}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.productionMonth',
                                            defaultMessage: '产品月份'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateProductionMonth} required>
                                        <LocalizeInputNumber
                                            min={0}
                                            max={12}
                                            name="productionMonth"
                                            precision={0}
                                            value={data.productionMonth}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.title',
                                            defaultMessage: '标题'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateTitle} required>
                                        <TextInput
                                            name="title"
                                            value={data.title}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.cargoDescription',
                                            defaultMessage: '货描'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCargoDescription} required>
                                        <TextInput
                                            name="cargoDescription"
                                            value={data.cargoDescription}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.model',
                                            defaultMessage: '车型编号'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateModel} required>
                                        <TextInput
                                            name="model"
                                            value={data.model}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.supplierId',
                                            defaultMessage: '供应商名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="supplierId"
                                            value={data.supplierId}
                                            options={this.props.initEnum.suppliers}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.address',
                                            defaultMessage: '地址'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.contactNumber',
                                            defaultMessage: '电话'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.zipCode',
                                            defaultMessage: '邮政编码'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.zipCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.formC.marketDepartmentName',
                                            defaultMessage: '大区'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.marketDepartmentName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                        <WrappedSelect
                                            name="currency"
                                            value={data.currency}
                                            options={currency.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.tradeMethod',
                                            defaultMessage: '贸易方式'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            disabled
                                            name="tradeMethodId"
                                            value={data.tradeMethodId}
                                            options={this.props.initEnum.tradeMethods}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.salesOrderPriceTerms',
                                        defaultMessage: '价格条款'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateSalesOrderPriceTerms} required>
                                        <WrappedSelect
                                            allowClear
                                            name="salesOrderPriceTerms"
                                            value={data.salesOrderPriceTerms}
                                            options={saleOrderPriceTerms.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.paymentType',
                                        defaultMessage: '付款方式'
                                    })} {...FORM_OPTIONS.item} validateStatus={validatePaymentType}>
                                        <WrappedSelect
                                            allowClear
                                            name="paymentType"
                                            value={data.paymentType}
                                            options={paymentType.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.deliveryTerms',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateDeliveryTerms} required>
                                        <WrappedSelect
                                            allowClear
                                            name="deliveryTerms"
                                            value={data.deliveryTerms}
                                            options={saleOrderTransportTypeForKd.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.shippingPort',
                                            defaultMessage: '发运港口'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateShippingPort} required>
                                        <WrappedSelect
                                            allowClear
                                            name="shippingPortId"
                                            value={data.shippingPortId}
                                            options={this.props.initEnum.shippingPorts}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.destinationPort',
                                            defaultMessage: '目的港口'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateDestinationPort} required>
                                        <TextInput
                                            name="destinationPort"
                                            value={data.destinationPort}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.bank',
                                            defaultMessage: '银行名称'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBank} required>
                                        <WrappedSelect
                                            name="bankId"
                                            options={this.state.bankList}
                                            value={data.bankId}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.bankNameEng',
                                            defaultMessage: '银行英文名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.bankNameEng}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.swift',
                                            defaultMessage: '银行识别码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.swift}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.bankAccount',
                                            defaultMessage: '银行账号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.bankAccount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={<Row>
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.intl.formatMessage({
                                        id: 'newPanel.details',
                                        defaultMessage: 'Sub PI配置清单'
                                    })}
                                </Col>
                            </Row>}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantitySum}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmountSum)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'newPanel.partDetails',
                                defaultMessage: 'Sub PI清单'
                            })}
                            extra={<Button
                                size="small"
                                onClick={this.onClickImportPartBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.import',
                                    defaultMessage: '导入清单'
                                })}
                            </Button>}>
                            <Table
                                className="white-space-nowrap"
                                columns={partColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={saleProformaPartDetails}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantity}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmount)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
                {
                    this.state.showPartImportPanel &&
                    <ImportPartPanel
                        onCancel={this.onClosePartImportPanel}
                        onImportChange={this.onPartImportChange} />
                }
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const tradeMethods = initData.tradeMethods ? initData.tradeMethods.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const suppliers = initData.suppliers ? initData.suppliers.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const shippingPorts = initData.shippingPorts ? initData.shippingPorts.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
            tradeMethods,
            suppliers,
            shippingPorts
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: (data, details, saleProformaPartDetails) => dispatch(onSubmit(data, details, saleProformaPartDetails)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
